import java.util.List;


public class For implements Comando {

	private AcaoSemantica inicial;
	private Expressao condicao;
	private Expressao apos;
	private List<AcaoSemantica> conteudo;

	public For(AcaoSemantica inicial, Expressao condicao, Expressao apos,
			List<AcaoSemantica> conteudo) {
		this.inicial = inicial;
		this.condicao = condicao;
		this.apos = apos;
		this.conteudo = conteudo;
	}

	@Override
	public String getCode() {
		StringBuffer sb = new StringBuffer();

		String labelExpr = ParserUtils.novoLabel();
		String labelCodigo = ParserUtils.novoLabel();
		String labelUpdate = ParserUtils.novoLabel();
		String labelFinal = ParserUtils.novoLabel();
		Integer regCond = null;

		sb.append(inicial.getCode());
		sb.append(System.lineSeparator());

		sb.append(labelExpr + ": ");
		String s1 = condicao.getCode();
		if (condicao.possuiRegistradorFinal()) {
			regCond = condicao.registradorFinal();
			sb.append(s1);
		} else {
			regCond = ParserUtils.novoRegistrador();
			sb.append("LD R" + regCond + ", " + s1);
		}
		sb.append(System.lineSeparator());
		
		sb.append("JNZ " + labelCodigo + ", R" + regCond);
		sb.append(System.lineSeparator());
		sb.append("JMP " + labelFinal);
		sb.append(System.lineSeparator());

		sb.append(labelCodigo + ": ");
		for (AcaoSemantica as : conteudo) {
			if (as instanceof Generico) {
				Generico g = (Generico) as;
				if (g.getNome().equals("break")) {
					sb.append("JMP " + labelFinal);
					sb.append(System.lineSeparator());
				} else if (g.getNome().equals("continue")) {
					sb.append("JMP " + labelExpr);
					sb.append(System.lineSeparator());
				}
			} else {
				sb.append(as.getCode());
				sb.append(System.lineSeparator());
			}
		}
		
		sb.append(labelUpdate + ": ");
		sb.append(apos.getCode());
		sb.append(System.lineSeparator());
		sb.append("JMP " + labelExpr);
		sb.append(System.lineSeparator());
		sb.append(labelFinal + ": ");
		return sb.toString();
	}

}
